<template>
  <div id="app">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="logo">
        <img
          src="../assets/main.png"
          style="height:40px; margin: auto;"
        >
      </div>
      <el-menu
        class="top-menu"
        mode="horizontal"
        :default-active="activeTopMenu"
        @select="handleTopMenuSelect"
      >
        <el-menu-item
          v-for="menu in topMenus"
          :key="menu.id"
          :index="menu.id"
        >
          <i
            v-if="menu.iconCss"
            :class="menu.iconCss"
          />
          <span slot="title">{{ menu.text }}</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-menu
        v-if="currentSubMenus.length > 0"
        class="side-menu"
        :default-active="activeLeftMenu"
        @select="handleLeftMenuSelect"
      >
        <template v-for="menu in currentSubMenus">
          <!-- 有子菜单的项 -->
          <el-submenu
            v-if="menu.items && menu.items.length"
            :key="menu.id"
            :index="menu.id"
          >
            <template slot="title">
              <i
                v-if="menu.iconCss"
                :class="menu.iconCss"
              />
              <span>{{ menu.text }}</span>
            </template>
            <el-menu-item
              v-for="submenu in menu.items"
              :key="submenu.id"
              :index="submenu.NavigationUrl"
            >
              <i
                v-if="submenu.iconCss"
                :class="submenu.iconCss"
              />
              <span>{{ submenu.text }}</span>
            </el-menu-item>
          </el-submenu>

          <!-- 没有子菜单的项 -->
          <el-menu-item
            v-else
            :key="menu.id"
            :index="menu.NavigationUrl"
          >
            <i
              v-if="menu.iconCss"
              :class="menu.iconCss"
            />
            <span>{{ menu.text }}</span>
          </el-menu-item>
        </template>
      </el-menu>

      <!-- 内容区 -->
      <div class="content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script>
import { GetNavigationMenus } from '@/api/index.js'

export default {
  name: 'AppLayout',
  data() {
    return {
      menuData: {
        Result: {
          TopMenus: [],
          LeftMenus: []
        }
      },
      // 当前选中的顶部菜单ID
      activeTopMenu: '',
      // 当前选中的左侧菜单URL
      activeLeftMenu: '',
      // 当前显示的子菜单列表
      currentSubMenus: [],
       isMenuLoaded: false // 添加标志位，标记菜单是否已加载

    }
  },
  computed: {
    // 顶部菜单列表
    topMenus() {
      return this.menuData.Result.TopMenus || [];
    },
    // 左侧菜单列表
    leftMenus() {
      return this.menuData.Result.LeftMenus || [];
    },
    currentRoutePath() {
      return this.$route.path;
    }
  },
  watch: {
    // 监听路由变化，当路由变化时更新激活的菜单
    currentRoutePath: {
      immediate: true,
      handler(newPath) {
        if (this.isMenuLoaded) {
          this.updateActiveMenuByRoute(newPath);
        }
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      console.log('init')
      GetNavigationMenus().then(res => {
        if (res.Code === 200) {

          this.menuData = res
          this.isMenuLoaded = true;
          // 默认选中第一个菜单
           if (this.currentRoutePath && this.currentRoutePath !== '/' && this.currentRoutePath !== '/AppLayout') {
            this.updateActiveMenuByRoute(this.currentRoutePath);
          } else if (this.topMenus.length > 0) {
            // 没有路由时，默认选中第一个菜单
            this.activeTopMenu = this.topMenus[0].id;
            this.handleTopMenuSelect(this.topMenus[0].id);
          }
        
        }
      })
    },
     // 根据路由路径更新激活的菜单
    updateActiveMenuByRoute(routePath) {
      // 在顶部菜单中查找匹配的路由
      const matchedTopMenu = this.findMenuByUrl(this.topMenus, routePath);
      
      if (matchedTopMenu) {
        this.activeTopMenu = matchedTopMenu.id;
        
        // 如果匹配的顶部菜单有子菜单，设置当前子菜单
        if (matchedTopMenu.items && matchedTopMenu.items.length > 0) {
          this.currentSubMenus = matchedTopMenu.items;
        } else {
          // 否则从LeftMenus中查找对应的子菜单
          const subMenus = this.leftMenus.filter(item => item.pid === matchedTopMenu.id);
          this.currentSubMenus = subMenus;
        }
        
        this.activeLeftMenu = routePath;
        return;
      }
      
      // 如果在顶部菜单中没找到，在左侧菜单中查找
      const matchedLeftMenu = this.findMenuByUrl(this.leftMenus, routePath);
      if (matchedLeftMenu) {
        // 找到对应的顶部菜单
        const parentTopMenu = this.topMenus.find(menu => menu.id === matchedLeftMenu.pid);
        if (parentTopMenu) {
          this.activeTopMenu = parentTopMenu.id;
          
          // 设置当前子菜单
          const subMenus = this.leftMenus.filter(item => item.pid === parentTopMenu.id);
          this.currentSubMenus = subMenus;
          this.activeLeftMenu = routePath;
        }
      }
    },

    // 在菜单树中查找包含指定URL的菜单项
    findMenuByUrl(menus, url) {
      for (const menu of menus) {
        if (menu.NavigationUrl === url) {
          return menu;
        }
        
        if (menu.items && menu.items.length > 0) {
          const found = this.findMenuByUrl(menu.items, url);
          if (found) return found;
        }
      }
      return null;
    },

    navigateTo(path) {
      this.$router.push(path)
    },
    
    handleTopMenuSelect(menuId) {
console.log(menuId)

      this.activeTopMenu = menuId;
      const menu = this.topMenus.find(m => m.id === menuId);

      if (!menu) return;

      // 如果当前菜单有直接URL，直接加载
      if (menu.NavigationUrl) {
        this.$router.push(menu.NavigationUrl);
        this.activeTopMenu = menu.id;
        this.currentSubMenus = [];
        return;
      }

      // 如果当前菜单有子菜单，显示子菜单
      if (menu.items && menu.items.length > 0) {
         this.currentSubMenus = menu.items;
        // 自动选择第一个子菜单
        const firstSubMenu = this.findFirstAvailableUrl(menu.items);
        if (firstSubMenu) {
          this.$router.push(firstSubMenu);
          this.activeLeftMenu = firstSubMenu;
        }
        return;
      }

      // 如果没有子菜单，查找LeftMenus中对应的子菜单
     const subMenus = this.leftMenus.filter(item => item.pid === menuId);
      if (subMenus.length > 0) {
        this.currentSubMenus = subMenus;
        // 自动选择第一个可用的子菜单
        const firstAvailableUrl = this.findFirstAvailableUrl(subMenus);
        if (firstAvailableUrl) {
          this.$router.push(firstAvailableUrl);
          this.activeLeftMenu = firstAvailableUrl;
        }
      } else {
        this.currentSubMenus = [];
      }
    },

    // 处理左侧菜单选择
    handleLeftMenuSelect(url) {
      this.activeLeftMenu = url;
      this.$router.push(url);
    },
     // 查找第一个可用的URL
    findFirstAvailableUrl(menus) {
      for (const menu of menus) {
        // 如果当前菜单有直接URL
        if (menu.NavigationUrl) {
          return menu.NavigationUrl;
        }
        // 如果当前菜单有子菜单，递归查找
        if (menu.items && menu.items.length > 0) {
          const url = this.findFirstAvailableUrl(menu.items);
          if (url) return url;
        }
      }
      return null;
    }

  }
}
</script>
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  height: 100%;
}

#app {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 - 新样式 */
.top-nav {
  height: 60px;
  background: rgb(25, 144, 255) !important;
  /* 顶部背景色 */
  color: white !important;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  margin-right: 30px;
  color: white;
}

.top-menu {
  flex: 1;
  height: 100%;
  background: rgb(25, 144, 255) !important;
}

.el-menu {}

.top-menu .el-menu {
  background: rgb(25, 144, 255) !important;
  border: none;
}

.top-menu .el-menu-item {
  color: white !important;
  /* 字体白色 */
  font-size: 16px;
  height: 60px;
  line-height: 60px;
  border-bottom: 3px solid transparent;
}

.top-menu .el-menu-item:hover,
.top-menu .el-menu-item.is-active {
  background: rgb(51, 126, 204) !important;
  /* 选中背景色 */
  color: white !important;
}

/* 主内容区 */
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧菜单 - 新样式 */
.side-menu {
  width: 220px;
  background: white;
  /* 左侧背景白色 */
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
  transition: width 0.3s;
}

.side-menu .el-menu {
  border-right: none;
}

.side-menu .el-submenu__title,
.side-menu .el-menu-item {
  height: 46px;
  line-height: 46px;
  color: black;
  /* 字体黑色 */
}

.side-menu .el-menu-item.is-active {
  color: rgb(25, 144, 255) !important;
  /* 选中字体颜色 */
  font-weight: 600;
}

.side-menu .el-submenu__title:hover,
.side-menu .el-menu-item:hover {
  background-color: #f5f7fa;
}

/* 内容区 */
.content {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background: #f0f2f5;
}

.content iframe {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 4px;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 16px;
}
</style>